package com.project.everywheretakeaway;

import java.util.List;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.app.ListActivity;
import android.app.LoaderManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class RestaurantsActivity extends ListActivity implements OnSharedPreferenceChangeListener,LoaderManager.LoaderCallbacks<Cursor> {

	public static final String MAP_PREFS = "MAP_PREF";
	RestaurantListAdapter adapter;
	LocationManager locationManager;
	
	static final private int MENU_PREFERENCES = Menu.FIRST+1;
	private static final int SHOW_PREFERENCES = 1;
	
	private static final String PREF_IP_ADDRESS = "PREF_IP_ADDRESS";
	
	private final LocationListener locationListener = new LocationListener() {
		
		public void onLocationChanged(Location location) {
						
			//SharedPreferences mySharedPreferences = getSharedPreferences(MAP_PREFS,Activity.MODE_PRIVATE);
			Context context = getApplicationContext();
			SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
			
			SharedPreferences.Editor editor = mySharedPreferences.edit();
			editor.putString("device_lat", String.valueOf(location.getLatitude()));
			editor.putString("device_lng", String.valueOf(location.getLongitude()));
			editor.apply();
			
			startLoader();
			
			// Voglio solo una volta il GPS, quindi dopo elimino il listener
			unregisterLocationListener();
			
		}
		public void onProviderDisabled(String provider) {}
		public void onProviderEnabled(String provider) {}
		public void onStatusChanged(String provider, int status, Bundle extras) {}
	};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		// Register this OnSharedPreferenceChangeListener
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		prefs.registerOnSharedPreferenceChangeListener(this);
		
		// GPS		
		
		String svcName = Context.LOCATION_SERVICE;
		locationManager = (LocationManager)getSystemService(svcName);
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		//criteria.setPowerRequirement(Criteria.POWER_LOW);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setSpeedRequired(true);
		criteria.setCostAllowed(true);
		// Best provider (il secondo parametro indica che vogliamo provider attivi)
		String provider = locationManager.getBestProvider(criteria, true);
		// Matching providers (il secondo parametro indica che vogliamo provider attivi)
		//List<String> matchingProviders = locationManager.getProviders(criteria,true);
		
		/*
		// Ultima locazione conosciuta
		Location l = locationManager.getLastKnownLocation(provider);
		
		SharedPreferences mySharedPreferences = getSharedPreferences(MAP_PREFS,Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPreferences.edit();
		if(l != null) {			
			
			editor.putString("device_lat", String.valueOf(l.getLatitude()));
			editor.putString("device_lng", String.valueOf(l.getLongitude()));
			
			
		} 
		editor.apply();
		*/
		
		// Adapter
		
		adapter = new RestaurantListAdapter(this,null);
		
		setListAdapter(adapter);
		
		//getLoaderManager().initLoader(0, null, this);
		
		// Chiede un singolo aggiornamento del GPS basato sui criteri richiesti
		Looper looper = null;
		locationManager.requestSingleUpdate(criteria, locationListener, looper);
		
		
	}
	
	public void startLoader() {
		
		getLoaderManager().initLoader(0, null, this);
	}
	
	public void unregisterLocationListener() {
		locationManager.removeUpdates(locationListener);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.earthquake, menu);
		return true;
		*/
		
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);
		return true;
		
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		super.onOptionsItemSelected(item);
		
		switch(item.getItemId()) {
			
			case MENU_PREFERENCES:
				
				Class c = UserPreferenceActivity.class;
				
				Intent i = new Intent(this, c);
				startActivityForResult(i, SHOW_PREFERENCES);
				return true;		
	
		}
	
		return false;		
		
	}	
	
	

	@Override
	public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

		CursorLoader loader = new CursorLoader(this, RestaurantProvider.CONTENT_URI, null, null, null, null);
		return loader;
		
	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

		// Prima ho creto un adapter senza cursor. Quando il loader ha finito di caricare i dati
		// inserisce il collegamento al cursore collegato all'adapter
		adapter.swapCursor(cursor);
		
	}

	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		
		adapter.swapCursor(null);
		
	}
	
	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		
		Context context = getApplicationContext();
		SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		//SharedPreferences mySharedPreferences = getSharedPreferences(MAP_PREFS,Activity.MODE_PRIVATE);
		SharedPreferences.Editor editor = mySharedPreferences.edit();
		editor.putString("id", (String)((TextView)v.findViewById(R.id.restaurant_id)).getText());
		editor.putString("name", (String)((TextView)v.findViewById(R.id.restaurant_name)).getText());
		editor.putString("lat", (String)((TextView)v.findViewById(R.id.restaurant_lat)).getText());
		editor.putString("lng", (String)((TextView)v.findViewById(R.id.restaurant_lng)).getText());
		editor.apply();
		
		Intent intent = new Intent(RestaurantsActivity.this, MyMapActivity.class);
		startActivity(intent);
		
		v.findViewById(R.id.restaurant_id);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
		
		// Ricarica il servizio web quando viene modificato l'indirizzo IP
		if(key.equals("PREF_IP_ADDRESS") || key.equals("PREF_PORT")) {
			
			//getLoaderManager().restartLoader(0, null, this);
			ContentResolver cr = getContentResolver();
			cr.update(RestaurantProvider.CONTENT_URI, null,null,null);
			
		}
		
	}

}
